package controller.uu;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import model.dao.UserDaoLocal;
import model.entity.User;
import controller.CUtil;
import controller.ur.SAuthorFollowRemove;

/**
 * Servlet implementation class SLoginOut
 */
public class SLoginOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@EJB
	private UserDaoLocal userDao;
	
	private Logger log=Logger.getLogger(SLoginOut.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SLoginOut() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String mail = (String)request.getParameter("mail");
		String password = (String)request.getParameter("password");
		
		if ((mail == null) || (mail.equals("")) || (password == null) || (password.equals(""))) {
			request.setAttribute("message", "Bad mail/password pair");
			CUtil.redirecter(request, response, "uu/VLogin.jsp");
			return;
		}
		
		User user = userDao.findMailPassword(mail, password);
		
		if (user != null) {	
			HttpSession session = request.getSession(true);
			session.setAttribute("user", user);
			log.info("User logged in: "+user.toString());
			CUtil.lastPageRedirect(request, response);
		}else{
			request.setAttribute("message", "Bad mail/password pair");
			CUtil.redirecter(request, response, "uu/VLogin.jsp");
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
